package com.demo.jvm.chapter2.heap;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class JavaMethodAreaOOM {

  /**
   * vm option -XX:PermSize=10M -XX:MaxPermSize=10M
   * -XX:MetaspaceSize=512m -XX:MaxMetaspaceSize=512m
   */
  public static void main(String[] args) {
    while (true) {
      for (MemoryPoolMXBean memoryPoolMXBean : ManagementFactory.getMemoryPoolMXBeans()) {
        if ("Metaspace".equals(memoryPoolMXBean.getName())) {
          System.out.println("已使用" + memoryPoolMXBean.getUsage().getUsed() / 1024 / 1024 + " mb");
        }
      }
      Enhancer enhancer = new Enhancer();
      enhancer.setSuperclass(OOMObject.class);
      enhancer.setUseCache(false);
      enhancer.setCallback(new MethodInterceptor() {
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
          return proxy.invokeSuper(obj, args);
        }
      });
      enhancer.create();
    }
  }

  static class OOMObject {

  }
}